package com.i1510.config.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = "com.i1510.mapper.mti", sqlSessionFactoryRef = "sqlSessionFactoryMti",
        sqlSessionTemplateRef = "sqlSessionTemplateMti")
public class MyBatisConfigMti {
    @Resource(name = "dataSourceMti")
    DataSource dataSourceMti;

    @Bean(name = "mtiTransactionManager")
    public DataSourceTransactionManager mtiTransactionManager(@Qualifier("dataSourceMti")DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionFactoryMti")
    public SqlSessionFactory sqlSessionFactoryMti() {
        SqlSessionFactory sessionFactory = null;
        try {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSourceMti);
            org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
            configuration.setCallSettersOnNulls(true);
            bean.setConfiguration(configuration);
            sessionFactory = bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sessionFactory;
    }

    @Bean(name = "sqlSessionTemplateMti")
    public SqlSessionTemplate sqlSessionTemplateMti() {
        return new SqlSessionTemplate(sqlSessionFactoryMti());
    }
}
